package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

type MyData struct {
	UserID1 string `json:"userID1"`
	UserID2 string `json:"userID2"`
	Data    string `json:"data"`
}

func main() {
	http.HandleFunc("/ws", handleWebSocket1)
	log.Fatal(http.ListenAndServe(":8088", nil))
}

func handleWebSocket1(w http.ResponseWriter, r *http.Request) {
	userID := r.URL.Query().Get("userID")
	log.Println("接收到的 userID:", userID)
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			// 允许跨域请求
			return true
		},
	}

	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("升级为WebSocket连接失败:", err)
		return
	}
	defer conn.Close()

	for {
		// 读取前端发送的消息
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读取WebSocket消息失败:", err)
			break
		}
		if err != nil {
			log.Println("解析JSON失败:", err)
			break
		}

		fmt.Println("收到WebSocket消息:", string(message))
		var myData MyData
		err = json.Unmarshal(message, &myData)
		if err != nil {
			log.Println("解析JSON失败:", err)
			return
		}
		fmt.Println("UserID1:", myData.UserID1+"向"+myData.UserID2+"发送消息:"+myData.Data)

		// 回复消息给前端
		reply := []byte("收到你的消息了！")
		err = conn.WriteMessage(websocket.TextMessage, reply)
		if err != nil {
			log.Println("回复WebSocket消息失败:", err)
			break
		}
	}
}
